import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:math' as math;
import 'dart:ui';

import 'package:douhuaxiangsu/page/sketchpad_color_setting.dart';
import 'package:douhuaxiangsu/widgets/tool_button.dart';
import 'package:douhuaxiangsu/services/artwork_service.dart';
import 'package:douhuaxiangsu/utils/common_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';

import '../entity/artwork_model.dart';
import '../entity/canvas_step_type.dart';
import '../entity/canvas_type.dart';
import '../entity/palette_model.dart';
import '../services/palette_service.dart';
import '../utils/constants_utils.dart';
import '../utils/image_utils.dart';
import '../widgets/toast.dart';
import 'canvas_setting.dart';
import '../widgets/grid_painter.dart';
import '../widgets/history_overlay.dart';

/// 画板页面
class SketchpadPage extends StatefulWidget {
  final ArtworkModel artworkModel;

  const SketchpadPage({super.key, required this.artworkModel});

  @override
  State<SketchpadPage> createState() => _SketchpadPageState();
}

class _SketchpadPageState extends State<SketchpadPage> {
  /// 作品数据
  ArtworkModel get artworkModel => widget.artworkModel;

  /// 控制交互式查看器变换的控制器
  late TransformationController _transformationController;

  /// 当前选中的工具
  CanvasStepType _selectedTool = CanvasStepType.edit;

  /// 最小和最大缩放比例
  final double minScale = 0.5, maxScale = 20;

  /// 单元格缩放大小
  double cellSize = 10;

  /// 上一次绘制的宽高
  double preWidth = 0.0, preHeight = 0.0;

  /// 判断是否修改;已修改则退出页面时保存
  bool modify = false;

  /// 画布状态控制器;true则允许拖动画布
  bool _enableInteractiveViewer = false;

  /// Stream流;通知[历史记录弹窗]更新
  final StreamController<int> _stepIndexController =
      StreamController<int>.broadcast();

  /// 历史记录弹窗
  OverlayEntry? overlayEntry;

  /// 临时存储的一步操作
  StepModel tmpStepModel = StepModel(
    operate: CanvasStepType.edit,
    jsonExecute: '',
    jsonUndo: '',
    execute: {},
    undo: {},
  );

  /// 跟踪当前在屏幕上的指针
  final Map<int, PointerEvent> _pointers = {};

  /// 临时存储的绘制点
  final List<Offset> _pointsCache = [];

  /// 当次操作时最大的手指点数,用于兼容触屏
  int maxPointCount = 0;

  @override
  void initState() {
    /// 加载像素图片
    if (artworkModel.canvas.canvasConfig.pointStyle.type == 'custom') {
      for (var colorItem in artworkModel.palette.data) {
        ImageUtils.loadImageFromBase64WithColor(
          artworkModel.canvas.canvasConfig.pointStyle.data,
          colorItem.color,
          width: 30,
          height: 30,
        ).then(
          (tmpImg) => {
            if (tmpImg != null)
              {
                setState(() {
                  artworkModel
                          .canvas
                          .canvasConfig
                          .pointStyle
                          .imageCacheMap[colorItem.color.toHexString()] =
                      tmpImg;
                }),
              },
          },
        );
      }
    }
    // 初始化变换控制器
    _transformationController = TransformationController();
    // 初始化颜色列表
    {
      if (artworkModel.palette.data.isEmpty) {
        PaletteService.queryLast().then((ps) {
          setState(() {
            if (ps != null) {
              artworkModel.palette = ps;
              _saveArtwork();
            } else {
              artworkModel.palette.id = 0;
              artworkModel.palette.data = ConstantsUtils.defaultPalette;
            }
          });
        });
      } else
      // 如果不为空,则从数据库重新加载
      if (artworkModel.palette.id != null && artworkModel.palette.id != 0) {
        PaletteService.queryById(artworkModel.palette.id!).then((ps) {
          setState(() {
            if (ps != null) {
              artworkModel.palette = ps;
            } else {
              artworkModel.palette.id = 0;
              _saveArtwork();
            }
          });
        });
      }
    }
    if (artworkModel.canvas.step.isEmpty) {
      artworkModel.canvas.step.add(
        StepModel(
          operate: CanvasStepType.init,
          jsonExecute: '',
          jsonUndo: '',
          execute: {},
          undo: {},
        ),
      );
    }
    // 判断step的index是否在范围之内
    if (artworkModel.canvas.stepIdx < 0 ||
        artworkModel.canvas.stepIdx >= artworkModel.canvas.step.length) {
      artworkModel.canvas.stepIdx = artworkModel.canvas.step.length - 1;
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    MediaQueryData mediaQuery = MediaQuery.of(context);
    // 包含安全区域的尺寸
    double safeWidth = mediaQuery.size.width;
    double safeHeight =
        mediaQuery.size.height -
        mediaQuery.padding.top -
        mediaQuery.padding.bottom;
    // print('height=$safeHeight ; width=$safeWidth');
    // 判断颜色选择器一行还是两行
    const double colorSelectorItemWidth = 40, colorSelectorItemPadding = 5;
    double totalColorSelectorItemWidth =
        artworkModel.palette.data.length *
        (colorSelectorItemWidth + (colorSelectorItemPadding * 2));
    int crossAxisCount = totalColorSelectorItemWidth > (safeWidth * 1.5)
        ? 2
        : 1;
    double colorSelectorItemHeight =
            (colorSelectorItemWidth + colorSelectorItemPadding * 2) *
            crossAxisCount,
        buttonTotalHeight = colorSelectorItemHeight + 150;
    // 颜色选择区域+工具按钮 高度按照200来
    if (safeHeight < buttonTotalHeight) {
      safeHeight = buttonTotalHeight;
    } else {
      safeHeight = safeHeight - buttonTotalHeight;
    }

    double minSize = math.min(safeWidth, safeHeight);
    int minCanvasSize = math.max(
      artworkModel.canvas.size.y,
      artworkModel.canvas.size.x,
    );
    // 计算单元格缩放
    for (int cs = 20; cs > 0; cs--) {
      cellSize = cs.toDouble();
      if ((minCanvasSize * cellSize) <= minSize) {
        break;
      }
    }

    // 首次绘制时设置缩放和位置
    if (safeWidth != preWidth || safeHeight != preHeight) {
      final canvasWidth = artworkModel.canvas.size.x * cellSize,
          canvasHeight = artworkModel.canvas.size.y * cellSize;
      //计算默认缩放比例
      double defaultScale = math.min(
        safeWidth / (canvasWidth),
        safeHeight / (canvasHeight),
      );
      if (defaultScale < minScale) {
        defaultScale = minScale;
      } else if (defaultScale > maxScale) {
        defaultScale = maxScale;
      }

      // 计算居中位置
      final double dx = safeWidth / 2 * (1 / defaultScale - 1);
      final dy = safeHeight / 2 * (1 / defaultScale - 1);
      _transformationController.value = Matrix4.identity()
        ..scale(defaultScale)
        ..translate(dx, dy);
      preWidth = safeWidth;
      preHeight = safeHeight;
    }
    return PopScope(
      onPopInvokedWithResult: (bool didPop, Object? result) {
        overlayEntry?.remove();
        overlayEntry = null;
      },
      child: Scaffold(
        appBar: AppBar(
          title: const Text('画板'),
          // 右上角按钮区域
          actions: [
            IconButton(
              icon: Icon(
                Icons.location_on,
                color: (artworkModel.canvas.canvasConfig.showPosition
                    ? IconTheme.of(context).color
                    : IconTheme.of(context).color?.withAlpha(127)),
              ),
              tooltip:
                  '${artworkModel.canvas.canvasConfig.showPosition ? '隐藏' : '显示'}坐标',
              onPressed: () {
                setState(() {
                  artworkModel.canvas.canvasConfig.showPosition =
                      !artworkModel.canvas.canvasConfig.showPosition;
                });
                _saveCanvasAsBase64();
              },
            ),
            IconButton(
              icon: Icon(Icons.undo, color: IconTheme.of(context).color),
              tooltip: '上一步',
              onPressed: () {
                if (artworkModel.canvas.stepIdx > 0) {
                  _chargeOperationHistory(artworkModel.canvas.stepIdx - 1);
                } else {
                  Toast.show('已经是第一步了', context);
                }
              },
            ),
            IconButton(
              icon: Icon(Icons.redo, color: IconTheme.of(context).color),
              tooltip: '下一步',
              onPressed: () {
                var tmpIdx = artworkModel.canvas.stepIdx + 1;
                if (tmpIdx < artworkModel.canvas.step.length) {
                  _chargeOperationHistory(tmpIdx);
                } else {
                  Toast.show('已经是最后一步了', context);
                }
              },
            ),
            IconButton(
              icon: Icon(Icons.history, color: IconTheme.of(context).color),
              tooltip: '历史操作',
              onPressed: () {
                _showOperationHistory(context);
              },
            ),
          ],
        ),
        body: Column(
          children: [
            SizedBox(
              width: safeWidth,
              height: safeHeight,
              child: InteractiveViewer(
                transformationController: _transformationController,
                boundaryMargin: const EdgeInsets.all(200),
                minScale: minScale,
                maxScale: maxScale,
                // 控制是否允许平移
                panEnabled: _enableInteractiveViewer,
                // 控制是否允许缩放
                scaleEnabled: _enableInteractiveViewer,
                child: Center(
                  child: SizedBox(
                    width: artworkModel.canvas.size.x * cellSize,
                    height: artworkModel.canvas.size.y * cellSize,
                    child: Listener(
                      // 监听鼠标点击
                      onPointerDown: (event) {
                        _pointers[event.pointer] = event;
                        maxPointCount = math.max(
                          maxPointCount,
                          _pointers.length,
                        );
                        if (_pointers.length == 1 && event.buttons == 1) {
                          double dx = event.localPosition.dx,
                              dy = event.localPosition.dy;
                          // 画笔
                          if (_selectedTool == CanvasStepType.edit) {
                            setState(() {
                              _enableInteractiveViewer = false;
                            });
                            _pointsCache.add(Offset(dx, dy));
                            // 取色
                          } else if (_selectedTool ==
                              CanvasStepType.eyedropper) {
                            _eyedropperEnter(dx, dy);
                            // 填充同色
                          } else if (_selectedTool ==
                              CanvasStepType.fillSameColor) {
                            setState(() {
                              _fillSameColorEnter(dx, dy);
                            });
                            // 填充区域
                          } else if (_selectedTool == CanvasStepType.fillArea) {
                            setState(() {
                              _fillAreaColorEnter(dx, dy);
                            });
                          }
                        } else {
                          setState(() {
                            _enableInteractiveViewer = true;
                          });
                        }
                      },
                      // 监听鼠标移动
                      onPointerMove: (event) {
                        if (_pointers.containsKey(event.pointer)) {
                          _pointers[event.pointer] = event;
                        }
                        maxPointCount = math.max(
                          maxPointCount,
                          _pointers.length,
                        );
                        if (_pointers.length == 1 && event.buttons == 1) {
                          if (_enableInteractiveViewer) {
                            setState(() {
                              _enableInteractiveViewer = false;
                            });
                          }
                          if (_selectedTool == CanvasStepType.edit) {
                            _onEnter(
                              event.localPosition.dx,
                              event.localPosition.dy,
                            );
                          }
                        } else {
                          if (!_enableInteractiveViewer) {
                            setState(() {
                              _enableInteractiveViewer = true;
                            });
                          }
                        }
                      },
                      // 监听鼠标离开
                      onPointerUp: (event) {
                        _pointers.remove(event.pointer);
                        // 当所有指针都离开时，重新启用InteractiveViewer交互
                        if (_pointers.isEmpty && !_enableInteractiveViewer) {
                          setState(() {
                            _enableInteractiveViewer = true;
                          });
                          if (maxPointCount == 1) {
                            if (_selectedTool == CanvasStepType.edit) {
                              for (var o in _pointsCache) {
                                _onEnter(o.dx, o.dy);
                              }
                              _pointsCache.clear();
                              _unEnter();
                            }
                          }
                          maxPointCount = 0;
                        }
                      },
                      onPointerCancel: (event) {
                        _pointers.remove(event.pointer);

                        // 当所有指针都离开时，重新启用InteractiveViewer交互
                        if (_pointers.isEmpty && !_enableInteractiveViewer) {
                          setState(() {
                            _enableInteractiveViewer = true;
                          });
                          _unEnter();
                        }
                      },
                      child: CustomPaint(
                        painter: GridPainter(
                          artworkModel: artworkModel,
                          cellSize: cellSize,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            const SizedBox(height: 10),
            // 颜色选择区域
            SizedBox(
              height: colorSelectorItemHeight,
              width: safeWidth,
              child: ScrollConfiguration(
                behavior: ScrollConfiguration.of(context).copyWith(
                  dragDevices: {
                    PointerDeviceKind.mouse,
                    PointerDeviceKind.touch,
                  },
                ),
                child: GridView.count(
                  crossAxisCount: crossAxisCount,
                  scrollDirection: Axis.horizontal,
                  children: artworkModel.palette.data
                      .asMap()
                      .entries
                      .where((entry) {
                        final colorItem = entry.value;
                        return colorItem.view;
                      })
                      .map((entry) {
                        final idx = entry.key;
                        final colorItem = entry.value;
                        return Padding(
                          padding: const EdgeInsets.symmetric(
                            horizontal: colorSelectorItemPadding,
                            vertical: colorSelectorItemPadding,
                          ),
                          child: GestureDetector(
                            onTap: () {
                              setState(() {
                                artworkModel.palette.lastUseColor = idx;
                              });
                              _saveArtwork();
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                color: colorItem.color,
                                border: artworkModel.palette.lastUseColor == idx
                                    ? Border.all(
                                        color:
                                            useWhiteForeground(colorItem.color)
                                            ? Colors.grey
                                            : Colors.black,
                                        width: 3,
                                      )
                                    : null,
                              ),
                              child: Center(
                                child: Text(
                                  colorItem.name,
                                  style: TextStyle(
                                    // fontSize: 12,
                                    color: useWhiteForeground(colorItem.color)
                                        ? Colors.white
                                        : Colors.black,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        );
                      })
                      .toList(),
                ),
              ),
            ),
            const SizedBox(height: 10),
            // 工具按钮
            SizedBox(
              height: 60,
              child: Padding(
                padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: ScrollConfiguration(
                  behavior: ScrollConfiguration.of(context).copyWith(
                    dragDevices: {
                      PointerDeviceKind.mouse,
                      PointerDeviceKind.touch,
                    },
                  ),
                  child: ListView(
                    scrollDirection: Axis.horizontal,
                    children: [
                      ToolButton(
                        icon: Icons.edit,
                        label: '编辑',
                        isSelected: _selectedTool == CanvasStepType.edit,
                        onTap: () {
                          setState(() {
                            _selectedTool = CanvasStepType.edit;
                          });
                        },
                      ),
                      const SizedBox(width: 20),
                      ToolButton(
                        icon: Icons.colorize,
                        label: '取色',
                        isSelected: _selectedTool == CanvasStepType.eyedropper,
                        onTap: () {
                          setState(() {
                            _selectedTool = CanvasStepType.eyedropper;
                          });
                        },
                      ),
                      const SizedBox(width: 20),
                      ToolButton(
                        icon: Icons.opacity,
                        label: '填充同色',
                        isSelected:
                            _selectedTool == CanvasStepType.fillSameColor,
                        onTap: () {
                          setState(() {
                            _selectedTool = CanvasStepType.fillSameColor;
                          });
                        },
                      ),
                      const SizedBox(width: 20),
                      ToolButton(
                        icon: Icons.format_color_fill,
                        label: '填充区域',
                        isSelected: _selectedTool == CanvasStepType.fillArea,
                        onTap: () {
                          setState(() {
                            _selectedTool = CanvasStepType.fillArea;
                          });
                        },
                      ),
                      const SizedBox(width: 20),
                      ToolButton(
                        icon: Icons.color_lens,
                        label: '颜色管理',
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => SketchpadColorSetting(
                                paletteModel: artworkModel.palette,
                              ),
                            ),
                          ).then(
                            (value) => {
                              setState(() {
                                if (value != null) {
                                  artworkModel.palette = value;
                                  if (value.id != null && value.id != 0) {
                                    PaletteService.updateById(value);
                                  }
                                  _saveArtwork();
                                }
                              }),
                            },
                          );
                        },
                      ),
                      const SizedBox(width: 20),
                      ToolButton(
                        icon: Icons.cleaning_services,
                        label: '清空画布',
                        onTap: () {
                          tmpStepModel.operate = CanvasStepType.clear;
                          tmpStepModel.execute = {};
                          tmpStepModel.undo = {};
                          CommonUtils.map2Iterable(
                            artworkModel.canvas.pointData,
                            (double x, double y, Color color) => {
                              CommonUtils.map2Put(
                                tmpStepModel.undo,
                                x,
                                y,
                                color,
                              ),
                            },
                          );
                          setState(() {
                            artworkModel.canvas.pointData.clear();
                          });
                          _unEnter();
                        },
                      ),
                      const SizedBox(width: 20),
                      ToolButton(
                        icon: Icons.aspect_ratio,
                        label: '画布设置',
                        onTap: () {
                          bool isShow = overlayEntry != null;
                          if (isShow) {
                            _showOperationHistory(context);
                          }
                          var ctx = context;
                          // 点击后跳转到设置页
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => CanvasSettingsPage(
                                artworkModel: artworkModel,
                              ),
                            ),
                          ).then(
                            (onValue) => {
                              setState(() {}),
                              if (isShow && ctx.mounted)
                                {_showOperationHistory(ctx)},
                              _saveCanvasAsBase64(),
                            },
                          );
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
            const SizedBox(height: 10),
          ],
        ),
      ),
    );
  }

  @override
  void deactivate() {
    // 移除overlayEntry
    overlayEntry?.remove();
    overlayEntry = null;
    super.deactivate();
  }

  @override
  void dispose() {
    // 关闭流
    _stepIndexController.close();
    _cleanTransparentPoints();
    if (modify) {
      _saveArtwork();
    }
    super.dispose();
  }

  /// 保存作品
  void _saveArtwork() {
    modify = true;
    ArtworkService.updateById(artworkModel);
  }

  /// 保存画布为base64
  void _saveCanvasAsBase64() async {
    try {
      // 创建一个 PictureRecorder 来记录绘制操作
      final recorder = PictureRecorder();
      double width = (artworkModel.canvas.size.x * cellSize),
          height = (artworkModel.canvas.size.y * cellSize);
      final canvasSize = Size(width, height);

      final canvas = Canvas(
        recorder,
        Rect.fromPoints(Offset.zero, Offset(width, height)),
      );

      // 使用 GridPainter 绘制当前画布内容
      final painter = GridPainter(
        artworkModel: artworkModel,
        cellSize: cellSize,
      );
      painter.paint(canvas, canvasSize);

      // 结束绘制并生成图片
      final picture = recorder.endRecording();
      if (kDebugMode) {
        print('canvasSize=$canvasSize');
      }
      final img = await picture.toImage(width.toInt(), height.toInt());

      // 转换为 PNG 字节数据
      final byteData = await img.toByteData(format: ImageByteFormat.png);
      if (byteData == null) return null;

      // 转换为 Base64 字符串
      final base64Data = base64Encode(byteData.buffer.asUint8List());
      artworkModel.image64 = base64Data;
      _saveArtwork();
    } catch (e) {
      if (kDebugMode) {
        print('保存图片时出错: $e');
      }
      return null;
    }
  }

  /// 初始化操作历史
  StepModel _initStepModel(CanvasStepType operate) {
    return StepModel(
      operate: operate,
      jsonExecute: '',
      jsonUndo: '',
      execute: {},
      undo: {},
    );
  }

  /// 编辑时鼠标按下/滑动
  void _onEnter(double dx, double dy) {
    final double x = CommonUtils.coverPoint2Idx(dx, cellSize),
        y = CommonUtils.coverPoint2Idx(dy, cellSize);
    // 位置在画布之外
    if (x >= artworkModel.canvas.size.x ||
        x < 0 ||
        y >= artworkModel.canvas.size.y ||
        y < 0) {
      return;
    }
    tmpStepModel.operate = _selectedTool;
    Color? c = CommonUtils.map2Get(artworkModel.canvas.pointData, x, y);
    CommonUtils.map2PutOnlyNull(
      tmpStepModel.undo,
      x,
      y,
      c ?? Colors.transparent,
    );
    setState(() {
      // 设置点的颜色
      CommonUtils.map2Put(
        artworkModel.canvas.pointData,
        x,
        y,
        artworkModel.palette.data[artworkModel.palette.lastUseColor].color,
      );
    });
    CommonUtils.map2Put(
      tmpStepModel.execute,
      x,
      y,
      artworkModel.palette.data[artworkModel.palette.lastUseColor].color,
    );
  }

  /// 编辑时鼠标抬起/停止滑动
  void _unEnter() {
    // 如果当前步骤idx不是最后一个,则删除之后的步骤(代表回滚操作之后又从中间做了操作)
    if (artworkModel.canvas.stepIdx != artworkModel.canvas.step.length - 1) {
      artworkModel.canvas.step.removeRange(
        artworkModel.canvas.stepIdx + 1,
        artworkModel.canvas.step.length,
      );
    }
    //先=length再添加元素,就不用添加后-1了
    artworkModel.canvas.stepIdx = artworkModel.canvas.step.length;
    artworkModel.canvas.step.add(tmpStepModel);
    tmpStepModel = _initStepModel(CanvasStepType.edit);
    _saveCanvasAsBase64();
    // 刷新悬浮窗口状态
    _stepIndexController.add(artworkModel.canvas.stepIdx);
  }

  /// 吸管工具按下
  void _eyedropperEnter(double dx, double dy) {
    final double x = CommonUtils.coverPoint2Idx(dx, cellSize),
        y = CommonUtils.coverPoint2Idx(dy, cellSize);
    // 位置在画布之外
    if (x >= artworkModel.canvas.size.x ||
        x < 0 ||
        y >= artworkModel.canvas.size.y ||
        y < 0) {
      return;
    }
    Color? c = CommonUtils.map2Get(artworkModel.canvas.pointData, x, y);
    if (c != null) {
      bool isExist = false;
      for (int i = 0; i < artworkModel.palette.data.length; i++) {
        if (artworkModel.palette.data[i].color == c) {
          setState(() {
            artworkModel.palette.lastUseColor = i;
          });
          isExist = true;
          break;
        }
      }
      if (!isExist) {
        artworkModel.palette.data.insert(
          0,
          ColorItem(name: '', description: '', view: true, color: c),
        );
        setState(() {
          artworkModel.palette.lastUseColor =
              artworkModel.palette.data.length - 0;
        });
      }
      _saveArtwork();
    }
  }

  /// 填充相同颜色
  void _fillSameColorEnter(double dx, double dy) {
    final double x = CommonUtils.coverPoint2Idx(dx, cellSize),
        y = CommonUtils.coverPoint2Idx(dy, cellSize);
    // 位置在画布之外
    if (x >= artworkModel.canvas.size.x ||
        x < 0 ||
        y >= artworkModel.canvas.size.y ||
        y < 0) {
      return;
    }
    Color? color = CommonUtils.map2Get(artworkModel.canvas.pointData, x, y);
    bool isEdit = false;
    _pointFullIterable((x, y, c) {
      if (c == null || c == Colors.transparent) {
        if (color == null || color == Colors.transparent) {
          _onEnter(x * cellSize, y * cellSize);
          isEdit = true;
        }
      } else if (color != null && c == color) {
        _onEnter(x * cellSize, y * cellSize);
        isEdit = true;
      }
    });
    if (isEdit) {
      _unEnter();
    }
  }

  /// 填充相连区域（油漆桶功能）
  void _fillAreaColorEnter(double dx, double dy) {
    final double startX = CommonUtils.coverPoint2Idx(dx, cellSize),
        startY = CommonUtils.coverPoint2Idx(dy, cellSize);

    // 检查坐标是否在画布范围内
    if (startX >= artworkModel.canvas.size.x ||
        startX < 0 ||
        startY >= artworkModel.canvas.size.y ||
        startY < 0) {
      return;
    }

    // 获取起始点的颜色
    Color? targetColor = CommonUtils.map2Get(
      artworkModel.canvas.pointData,
      startX,
      startY,
    );
    Color fillColor =
        artworkModel.palette.data[artworkModel.palette.lastUseColor].color;

    // 如果目标颜色和填充颜色相同，则无需操作
    if (targetColor == fillColor) {
      return;
    }

    bool isEdit = false;
    if (artworkModel.canvas.type == CanvasType.square) {
      // 使用队列实现广度优先搜索(BFS)来查找相连区域
      Queue<Offset> queue = Queue();
      Set<String> visited = <String>{};

      queue.add(Offset(startX, startY));
      visited.add('$startX,$startY');

      // 四个方向：上、右、下、左
      List<Offset> directions = [
        Offset(0, -1), // 上
        Offset(1, 0), // 右
        Offset(0, 1), // 下
        Offset(-1, 0), // 左
      ];

      while (queue.isNotEmpty) {
        Offset current = queue.removeFirst();
        double x = current.dx;
        double y = current.dy;

        // 填充当前点
        _onEnter(x * cellSize, y * cellSize);
        isEdit = true;

        // 检查四个方向的相邻点
        for (Offset direction in directions) {
          double nextX = x + direction.dx;
          double nextY = y + direction.dy;

          // 检查相邻点是否在画布范围内
          if (nextX >= 0 &&
              nextX < artworkModel.canvas.size.x &&
              nextY >= 0 &&
              nextY < artworkModel.canvas.size.y) {
            String key = '$nextX,$nextY';

            // 如果该点未被访问过
            if (!visited.contains(key)) {
              visited.add(key);

              // 获取相邻点的颜色
              Color? nextColor = CommonUtils.map2Get(
                artworkModel.canvas.pointData,
                nextX,
                nextY,
              );

              // 如果相邻点颜色与目标颜色相同（或都为透明），则加入队列
              if ((targetColor == null || targetColor == Colors.transparent) &&
                  (nextColor == null || nextColor == Colors.transparent)) {
                queue.add(Offset(nextX, nextY));
              } else if (nextColor != null && nextColor == targetColor) {
                queue.add(Offset(nextX, nextY));
              }
            }
          }
        }
      }
    } else {
      CommonUtils.showToast('还未实现其他形状', context);
    }
    // 如果有修改，则记录操作步骤
    if (isEdit) {
      _unEnter();
    }
  }

  /// 迭代画布所有点
  void _pointFullIterable(Function(double x, double y, Color? color) callback) {
    SizeModel size = artworkModel.canvas.size;
    // 正方形
    if (artworkModel.canvas.type == CanvasType.square) {
      for (double x = 0; x < size.x; x++) {
        for (double y = 0; y < size.y; y++) {
          callback(
            x,
            y,
            CommonUtils.map2Get(artworkModel.canvas.pointData, x, y),
          );
        }
      }
    } else {
      CommonUtils.showToast('还未实现其他形状', context);
    }
  }

  /// 显示操作历史
  void _showOperationHistory(BuildContext context) {
    if (overlayEntry != null) {
      overlayEntry?.remove();
      overlayEntry = null;
    } else {
      overlayEntry = OverlayEntry(
        builder: (context) => HistoryOverlay(
          title: '操作历史',
          onClose: () {
            overlayEntry!.remove();
            overlayEntry = null;
          },
          child: StreamBuilder<int>(
            stream: _stepIndexController.stream,
            initialData: artworkModel.canvas.stepIdx,
            builder: (context, snapshot) {
              return Material(
                child: ListView(
                  padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                  children: artworkModel.canvas.step
                      .asMap()
                      .entries
                      .map((entry) {
                        final idx = entry.key;
                        final sm = entry.value;
                        final isFutureStep = idx > snapshot.data!;
                        return ListTile(
                          onTap: () {
                            _chargeOperationHistory(idx);
                          },
                          title: Text(
                            '$idx: ${sm.operate.name}',
                            style: TextStyle(
                              color: isFutureStep ? Colors.grey : Colors.black,
                            ),
                          ),
                        );
                      })
                      .toList()
                      .reversed
                      .toList(),
                ),
              );
            },
          ),
        ),
      );
      Overlay.of(context).insert(overlayEntry!);
    }
  }

  /// 执行/回滚到某一步
  void _chargeOperationHistory(int idx) {
    // 同一步,无修改
    if (artworkModel.canvas.stepIdx == idx) {
      return;
    }
    // 回滚
    if (artworkModel.canvas.stepIdx > idx) {
      for (int i = artworkModel.canvas.stepIdx; i > idx; i--) {
        StepModel stepModel = artworkModel.canvas.step[i];
        switch (stepModel.operate) {
          case CanvasStepType.resize:
            var jsonMap = jsonDecode(stepModel.jsonUndo);
            artworkModel.canvas.size.x = jsonMap['x'] as int;
            artworkModel.canvas.size.y = jsonMap['y'] as int;
            break;
          default:
            CommonUtils.map2Iterable(stepModel.undo, (
              double x,
              double y,
              Color color,
            ) {
              CommonUtils.map2Put(artworkModel.canvas.pointData, x, y, color);
            });
        }
      }
      // 向后执行
    } else {
      for (int i = artworkModel.canvas.stepIdx; i <= idx; i++) {
        StepModel stepModel = artworkModel.canvas.step[i];
        switch (stepModel.operate) {
          case CanvasStepType.clear:
            artworkModel.canvas.pointData.clear();
            break;
          case CanvasStepType.resize:
            var jsonMap = jsonDecode(stepModel.jsonExecute);
            artworkModel.canvas.size.x = jsonMap['x'] as int;
            artworkModel.canvas.size.y = jsonMap['y'] as int;
            break;
          default:
            CommonUtils.map2Iterable(stepModel.execute, (
              double x,
              double y,
              Color color,
            ) {
              CommonUtils.map2Put(artworkModel.canvas.pointData, x, y, color);
            });
        }
      }
    }
    setState(() {
      artworkModel.canvas.stepIdx = idx;
    });
    // 通知 overlay 更新
    _stepIndexController.add(idx);
    _saveCanvasAsBase64();
  }

  /// 清除透明色
  void _cleanTransparentPoints() {
    final pointData = artworkModel.canvas.pointData;
    final keysToRemove = <double>[];

    pointData.forEach((xKey, yMap) {
      // 移除所有透明颜色的点
      yMap.removeWhere((yKey, color) => color == Colors.transparent);

      // 如果y轴映射为空，标记x轴键以待移除
      if (yMap.isEmpty) {
        keysToRemove.add(xKey);
      }
    });

    // 移除所有空的y轴映射
    for (var key in keysToRemove) {
      pointData.remove(key);
    }
  }
}
